# encoding: utf-8

# 获取当期所有参与者预测排名(微服务接口, 支持分页)

module Capevaluation
  module Business
    module Prediction

      #curl http://127.0.0.1:5678/api -d cmd=predict_get_rankings -d type=1 -d gzip=0
      #curl http://127.0.0.1:5678/api -d cmd=predict_get_rankings -d type=0 -d page=2 -d count=5 -d gzip=0
      def predict_get_rankings(params)
        #self.logger.debug(CaiQiu::Support::Utils.get_backtrace_list)
        self.logger.debug(__method__.to_s + " params:#{params}")

        #1.检验参数是否为空
        raise Capevaluation::Exception::LackOfParams.new if params['type'].nil?

        #2.验证参数有效性
        #验证type字段
        type = params['type'].to_i
        raise Capevaluation::Exception::InvalidParams.new if !type.zero? && type!=1 && type!=2

        #3. 从redis中获取结果
        ranking_results = self.redis.get("capevaluation.ranking.#{type}")
        if !ranking_results.nil?
          return {:code => 0, :msg => '', :resp => [ranking_results]}
          #return JSON.parse(ranking_results)
        end

        #4.设置分页参数
        current_page = params['page']
        count = params['count']
        if current_page.nil?
          current_page = Capevaluation::Constant::Consumer::FIRST_PAGE
        end
        if count.nil?
          count = Capevaluation::Constant::Consumer::PAGE_COUNT
        end

        #5.根据type，整理参数
        sql_message = ""
        case type
          when 0 then sql_message = "where type = '0'"
          when 1 then sql_message = "where type = '1'"
          when 2 then sql_message = ""
        end
        params_new = {
            :type => type,
            :sql_message => sql_message,
            :page => current_page.to_i,
            :count => count.to_i
        }

        #6.得到结果
        ranking_results,total_page = Capevaluation::Service::PlayerScore.get_record_by_type(params_new)

        prediction = []
        result_count = 0
        ranking_results.each do|ranking_result|
          prediction_in = {
              "player" => ranking_result[:player],
              "total" => ranking_result[:total],
              "success" => ranking_result[:success],
              "fail" => ranking_result[:fail],
              "ratio" => ranking_result[:ratio],
              "score" => ranking_result[:score],
              "ranking" => ranking_result[:ranking]
          }
          prediction.push prediction_in
        end

        resp = {
            "page" => current_page.to_i+1,    #当前页数
            "total_page" => total_page, #总页数
            "prediction" => prediction
        }
        result = {:code => 0, :msg => '', :resp => [resp]}
        self.redis.setex("capevaluation.ranking.#{type}", 30, resp)
        return result
      end



    end
  end
end
